package com.terdidik.smsserver.interfaces;

import java.util.Collection;
import java.util.Properties;

import org.smslib.AGateway;
import org.smslib.InboundMessage;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.Message.MessageTypes;
import org.smslib.helper.Logger;
import org.smslib.smsserver.SMSServer;
import org.smslib.smsserver.interfaces.Interface;

public class Administrator extends Interface<Integer> {
	
	public Administrator(String myInfId, Properties myProps,
			SMSServer myServer,
			org.smslib.smsserver.interfaces.Interface.InterfaceTypes myType) {
		super(myInfId, myProps, myServer, myType);
		setDescription("Administration Tnterface.");
	}

	@Override
	public void messagesReceived(Collection<InboundMessage> msgList)
			throws Exception {
		for(InboundMessage im : msgList) {
			if((im.getType()==MessageTypes.INBOUND) && 
					(im.getText().toLowerCase().startsWith(getProperty("prefix", "sudo").toLowerCase())) &&
					(im.getText().toLowerCase().endsWith(getProperty("key", "1234").toLowerCase()))) {
				Logger.getInstance().logDebug("SMSServer: Interface ADMINISTRATION: " + im.getText(), null, null);
				String[] commands=im.getText().toLowerCase().split(" ");
				if((commands.length > 4) && (commands[1].toLowerCase().equals("ussd"))) {
					//prefix ussd number gateway key
					AGateway gw=Service.getInstance().getGateway(commands[3]);
					if(gw!=null) {
						String result=gw.sendUSSDCommand(commands[2], false);
						OutboundMessage om=new OutboundMessage(im.getOriginator(), "USSD RESULT:"+result);
						
						if(Service.getInstance().getGateway(im.getGatewayId()).isOutbound()){
							Service.getInstance().queueMessage(om, im.getGatewayId());
						} else {
							Service.getInstance().queueMessage(om);
						}
					} else {
						OutboundMessage om=new OutboundMessage(im.getOriginator(), "No gateway named "+commands[3]);
						if(Service.getInstance().getGateway(im.getGatewayId()).isOutbound()){
							Service.getInstance().queueMessage(om, im.getGatewayId());
						} else {
							Service.getInstance().queueMessage(om);
						}
					}
					
				}
			}
		}
	}

	@Override
	public Collection<OutboundMessage> getMessagesToSend() throws Exception {
		// TODO Auto-generated method stub
		return super.getMessagesToSend();
	}

}
